package server;

import channel.MyChannelInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


/**
 * @author yuzk
 * @date 2018/1/12
 */
public class TcpServer {

    private static Logger logger = LoggerFactory.getLogger(TcpServer.class);

    private int port;

    public TcpServer(int port){
        this.port = port;
    }

    public void start(){
        EventLoopGroup group = new NioEventLoopGroup();
        try{
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(group).channel(NioServerSocketChannel.class).localAddress(port)
                    .childHandler(new MyChannelInitializer())
                    .bind()
                    .sync()
                    .channel()
                    .closeFuture()
                    .sync();
        }catch (Exception e){
            logger.debug("ServerBootstrap start error :" + e.getMessage());
        }finally {
            try {
                group.shutdownGracefully().sync();
            }catch (Exception e){
                logger.debug("EventLoopGroup shutdown error :" + e.getMessage());
            }
        }
    }

    public static void main(String[] args) throws Exception{
        TcpServer server = new TcpServer(6000);
        server.start();
    }

}
